package com.juben.svr.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.juben.svr.domain.Email_validation;
import com.juben.svr.mapper.Emailmapper;
import com.juben.svr.mapper.usermapper;
import com.juben.svr.service.EmailValidationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.juben.svr.domain.Enum.EmailType.忘记密码邮箱验证;

@Service
public class Email_ValidationImpl implements EmailValidationService {
    @Autowired
    private Emailmapper emailmapper;

    @Autowired
    JavaMailSender javaMailSender;

    public Email_validation getEmailValidation(Email_validation emailValidation){
        Email_validation email_validation=emailmapper.getEmailValidation(emailValidation);
        return email_validation;
    }
    //删除验证码
    public boolean deleteEmailValidation(Email_validation email_validation){
        return emailmapper.deleteEmailValidation(email_validation);
    }


    //密码找回验证
    public boolean passEmailValidation(String email){
        try {
            System.out.println("密码找回邮件发送服务：");
            System.out.println("email:"+email);
            SimpleMailMessage message = new SimpleMailMessage();
            DateTime now = DateUtil.date(); // 获取当前时间
            message.setSentDate(now);
            message.setSubject("【幕起云端】密码找回");  // 邮件主题
            String code = RandomUtil.randomNumbers(6);
            message.setText("您的账号密码找回验证码为："+code+",有效期5分钟；请妥善保管，请勿泄露给他人。\n如非本人操作，请忽略。");
            message.setTo(email);
            message.setFrom("2811097455@qq.com");
            javaMailSender.send(message);

            //将验证码存入数据库

            System.out.println("将验证码存入数据库");
            Email_validation email_validation = new Email_validation();
            email_validation.setCode(code);
            email_validation.setEmail(email);
            email_validation.setEmailType(忘记密码邮箱验证);
            System.out.println("now:"+now);
            //将时间往后偏移5分钟
            Date updatedTime = DateUtil.offsetMinute(now, 5);
            email_validation.setTime(
                    DateUtil.format(updatedTime, "yyyy-MM-dd HH:mm:ss")
            );
            System.out.println("email_validation:"+email_validation);
            emailmapper.addEmailValidation(email_validation);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
